#pragma once
#include <pthread.h>
#include <functional>
#include <string>

using func_t = std::function<void(const std::string &)>;

class Thread
{
public:
    Thread(const std::string &name, func_t func) : _name(name), _func(func) {}
    void Excute()
    {
        _isrunning = true;
        _func(_name);
        _isrunning = false;
    }

    static void *ThreadRoutine(void *args)
    {
        Thread *self = static_cast<Thread *>(args); // 获得当前对象,agrs是this
        self->Excute();                             // 执行线程
        return nullptr;                             // 为防止出现无匹配返回值编译错误
    }

    bool Start()
    {
        int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
        if (n != 0)
            return false;
        return true;
    }

    std::string Status()
    {
        if (_isrunning)
            return "running";
        else
            return "seelp";
    }

    void Stop()
    {
        if (_isrunning)
        {
            _isrunning = false;
            pthread_cancel(_tid);
        }
    }

    void Join()
    {
        pthread_join(_tid, nullptr);
    }

    std::string Name()
    {
        return _name;
    }

private:
    std::string _name;
    pthread_t _tid;
    bool _isrunning;
    func_t _func; // 线程要执行的回调函数
};